import os
import xlwt
import configparser
from aip import AipOcr
#coding:utf-8

def field_split(txt):
    #print(txt)
    #print("AAAAAAAAA")
    if ":" in txt:
        content = txt.split(":")
        return content[1]
    else:
        return txt


def write_to_excel(result, filename):
    wb = xlwt.Workbook()
    sh1 = wb.add_sheet(filename, cell_overwrite_ok=True)
    sh1.write(0,0,'单号')
    sh1.write(0,1,'城市')
    sh1.write(0,2,'市县')
    sh1.write(0,3,'日期')
    sh1.write(0,4,'客户')
    sh1.write(0,5,'收货人')
    sh1.write(0,6,'运费支付方')
    sh1.write(0,7,'总件数')
    sh1.write(0,8,'总重')
    sh1.write(0,9,'送货地址')
    sh1.write(0,10,'销售联系人')
    sh1.write(0,11,'备注')
    col = 1
    remark_flag = True
    try:
        for i in range(int(result['words_result_num'])):
            txt = result['words_result'][i]['words']
            #print("\ntxt ", i, " is ")
            #print(txt)
            if txt.startswith('运输单号'):
                sh1.write(col, 0, field_split(txt))
            elif txt.startswith('城市'):
                sh1.write(col, 1, field_split(txt))
            elif txt.startswith('日期'):
                sh1.write(col, 3, field_split(txt))
            elif txt.startswith('客户'):
                sh1.write(col, 4, field_split(txt))
            elif txt.startswith("收货人"):
                sh1.write(col, 5, field_split(txt))
            elif txt.startswith('运费支付方'):
                sh1.write(col, 6, field_split(txt))
            elif txt.startswith('总件数'):
                sh1.write(col, 7, field_split(txt))
            elif txt.startswith('总重'):
                sh1.write(col, 8, field_split(txt))
            elif txt.startswith('送货地址'):
                sh1.write(col, 9, field_split(txt))
            elif txt.startswith('销售联系人'):
                sh1.write(col, 10, field_split(txt))
            elif txt.startswith('备注'):
                if remark_flag:
                    sh1.write(col, 11, field_split(txt))
                    remark_flag = False
            else:
                #print("OTHERS")
                #print(i)
                pass
    except:
        print("except")
        print(i)
        print(txt)
        pass
    wb.save(filename)

def get_config2():
    config = configparser.ConfigParser()
    print(config.sections())
    #config.read("c.txt", encoding="utf-8")
    config.read("config.ini", encoding="utf-8")
    print(config.sections())
    print("Info: Get_config2 done")

def get_config():
    global file_cnt
    global working_dir
    global interval
    global app_id
    global api_key
    global secret_key
    if os.path.isfile("./config.txt"):
        print("Info: Checking file ./config.txt")
        f_config = open("./config.txt", 'r')
        lines = f_config.readlines()
        for line in lines:
            if line.startswith('#'):
                continue
            elif line.count('\n')==len(line):
                continue
            else:
                print(line.split(':')[0])
                print(line.split(':')[1])
                line.split(':')[0] = line.split(':')[1]
                if line.split(':')[0] == 'working_dir':
                    working_dir = line.split(':')[1]
                elif line.split(':')[0] == 'app_id':
                    app_id = line.split(':')[1]
        #for line in f_config:
        #    print(line.rstrip())
        f_config.close()

        #with open("./config.txt") as file_obj:
        #    for content in file_obj:
        #        print(content.rstrip())
    else:
        print("Warning: No file ./config.txt found, no configuration")

    return

if __name__ == '__main__':
    file_cnt = 0
    working_dir = "./"
    interval    = 10
    app_id = ''
    api_key = ''
    secret_key = ''

    get_config2()
    print(working_dir)
    print(interval)
    print(app_id)


    for file in os.listdir(working_dir):
        if file.lower().endswith('.jpg'):
            image = open(working_dir+file, 'rb' ).read()
            if not os.path.isfile(working_dir+file+'.done'):
                fd = open(working_dir+file+'.done', mode="w", encoding="utf-8")
                fd.close()
        else:
            continue
        #image.close()
        file_cnt = file_cnt + 1
    print("file_cnt = ", file_cnt)

    print("Hello world!\n")

#   package an exe file
#   https://blog.csdn.net/u013541325/article/details/107858280


#    APP_ID = '23580782'
#    API_KEY = 'qalPikM6nw3X4yDqIhXPwO5G'
#    SECRECT_KEY = 'F86ATNVvDdtqli8U0ESsKMnvsgzRqLlD'
#    client = AipOcr(APP_ID, API_KEY, SECRECT_KEY)
#
#    options = {}
#    options["detect_direction"] = "false"
#    options["probability"] = "true"
#
#    fout = open("result.txt", "w", encoding='utf-8')
#
#    for file in os.listdir("./"):
#        if file.lower().endswith('.jpg'):
#            image = open("./"+file, 'rb' ).read()
#        else:
#            continue
#        result = client.basicAccurate(image, options)
#        write_to_excel(result, file+'.xls')
#
#        #num = int(result['words_result_num'])
#        #print("Num is ")
#        #print(num)
#        try:
#            for i in range(int(result['words_result_num'])):
#                txt = result['words_result'][i]['words']
#                #print("\ntxt ", i, " is ")
#                #print(txt)
#                if len(txt) > 2:
#                    fout.write(txt+'\n')
#        except:
#            print("except")
#            pass
#
#    fout.close()
#
#    print("Hello world!\n")